/************************************************************************************************
 * test examples of 100 interesting program in C
 * test 087.c
 * Special Checkers
 ***********************************************************************************************/

#include <stdio.h>

#define CHESSMAN 3

/*
 * look into the print result of whole moving procedure
 * there's a beautiful waveform
 */

int check(char* chessboard)
{
    int i;
    for (i = 0; i < CHESSMAN; i++)
        if (chessboard[i] != 'b' || chessboard[CHESSMAN*2-i] != 'w')
            return(0);
    return(1);
}

void swap(char* chessboard, int i, int j, int* blank)
{
    char temp = chessboard[i];
    chessboard[i] = chessboard[j];
    chessboard[j] = temp;
    if (chessboard[i] == ' ') *blank = i;
    else if (chessboard[j] == ' ') *blank = j;
}

void print(char* chessboard)
{
    printf("%s\n", chessboard);
}

int main()
{
    char chessboard[CHESSMAN*2+2];
    int i;
    int blank = CHESSMAN;
    for (i = 0; i < CHESSMAN; i++)
    {
        chessboard[i] = 'w';
        chessboard[CHESSMAN*2-i] = 'b';
    }
    chessboard[CHESSMAN] = ' ';
    chessboard[CHESSMAN*2+1] = 0;

    print(chessboard);
    while (1)
    {
        int i;
        int flag = 0; // mark for 1 step is moved
        for (i = CHESSMAN*2-2; flag == 0 && i >= 0; i--)
            if (chessboard[i] == 'w' && chessboard[i+1] == 'b' && chessboard[i+2] == ' ')
            {
                swap(chessboard, i, i+2, &blank);
                flag = 1; // the result shows: if we comment this flag estimation, the loop will also perform just 1 move. but how to prove?
            }
        for (i = 0; flag == 0 && i <= CHESSMAN*2-2; i++)
            if (chessboard[i] == ' ' && chessboard[i+1] == 'w' && chessboard[i+2] == 'b')
            {
                swap(chessboard, i, i+2, &blank);
                flag = 1;
            }
        if (!(blank>1 && blank<CHESSMAN*2 && chessboard[blank-1] == 'w' && chessboard[blank-2] == 'b' && chessboard[blank+1] == 'b')
            && flag == 0 && chessboard[blank-1] == 'w')
        {
            swap(chessboard, blank, blank-1, &blank);
            flag = 1;
        }
        if (!(blank>0 && blank<CHESSMAN*2-1 && chessboard[blank-1] == 'w' && chessboard[blank+1] == 'b' && chessboard[blank+2] == 'w')
            && flag == 0 && chessboard[blank+1] == 'b')
        {
            swap(chessboard, blank, blank+1, &blank);
            flag = 1;
        }

        print(chessboard);

        if (check(chessboard) == 1)
            break;
    }
}

